<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreDepartmentRequest;
use App\Http\Requests\UpdateDepartmentRequest;
use App\Models\Department;
use App\Models\User;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return ["departments" => Department::all(), "users_count" => User::all()->count()];
    }


    public function store(StoreDepartmentRequest $request)
    {
        Department::create($request->input());
        return $this->success("创建成功");
    }


    public function update(UpdateDepartmentRequest $request, Department $department)
    {
        $department->update($request->input());
        return $this->success("修改成功");
    }

    public function destroy(Department $department)
    {
        $department->delete();
        return $this->success("删除成功");
    }

    public function users(Request $request,Department $department)
    {
        return User::searchFields($request->all())->where("department_id", $department->id)->paginate(10);
    }

//    绑定管理员
    public function bindManager(Request $request, Department $department)
    {
        $department->manager()->sync($request->input('user_id'));
        return $this->success("绑定成功");
    }

    public function unBindManager(Request $request, Department $department)
    {
        $department->manager()->detach($request->input('user_id'));
        return $this->success("解绑成功");
    }
}
